# -*- coding: utf-8 -*-
# @Time: 2022/5/2 15:29

import os
from Common.mysql import app
from flask_cors import CORS
from flask import request

# 允许前端跨域
CORS(app, supports_credentials=True)


@app.route('/case_data/upload', methods=['POST', 'OPTIONS'])
def upload_case():
    """
    导入测试用例
    """

    # 拦截客户端发起的 OPTIONS 请求，并返回 204 状态码
    if request.method == 'OPTIONS':
        res = {
            'code': 204,
            'message': 'success',
            'data': []
        }

        return res

    # 获取前端传过来的文件，保存到指定目录UPLOAD_PATH
    uploaded_file = request.files['file']
    case_name = request.headers.get('Casename')
    filename = uploaded_file.filename
    if filename != '':
        file_ext = os.path.splitext(filename)[1]
        if file_ext not in app.config['CASE_UPLOAD_EXTENSIONS']:
            return '404'
        new_name = case_name+'.xmind'
        uploaded_file.save(os.path.join(app.config['CASE_UPLOAD_PATH'], new_name))

    # 解决跨域问题，响应头添加头部信息
    headers = {
        'Content-Type': 'multipart/form-data',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'OPTIONS, POST',
        'Access-Control-Expose-Headers': 'Content-Type,Accept,Origin,User-Agent',
        'Accept-Encoding': 'gzip, deflate, br'
    }
    res = {
        'code': 20000,
        'message': 'success',
        'data': []
    }
    return res, 200, headers
